package com.shimao.celnet.payment.controller.apinotcheck;


import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayCUPUser;
import com.shimao.celnet.payment.model.PPayCust;
import com.shimao.celnet.payment.service.PPayCupUserService;
import com.shimao.celnet.payment.service.PPayCustService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.service.SCodeNameService;
import com.shimao.celnet.payment.service.impl.apiservice.CallOut_TLPublicService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 通联支付请求 支付平台-->通联
 * 2017/12/14
 * christ
 */

@RestController
@RequestMapping(value = "/payTL")
public class CallOut_allinPayReqOutController {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private PPayService pPayService;

    @Autowired
    private PPayCustService pPayCustService;

    @Autowired
    private ConstantConfig constantConfig;

    @Autowired
    private CallOut_TLPublicService callOut_tlPublicService;

    @Autowired
    private SCodeNameService sCodeNameService;

    @Autowired
    private PPayCupUserService pPayCupUserService;

    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public Object payToTL(@RequestParam(value = "paymentId") String paymentId, @RequestParam(value = "pType") String pType) throws Exception {

        if (paymentId != null && paymentId !=""){
            String TimeStamp = String.valueOf(System.currentTimeMillis());//时间戳，用于商户交易订单号
            //根据guid查询数据库中的账单表
            PPay pPay = pPayService.getByKey(paymentId);
            //根据小区sfid获取商户信息
            PPayCust pPayCust = getTLMessage(pPay.getEstateGuid(),pType);
            if ("A01".equals(pType)){      //支付宝
                logger.info("****************支付支付开始******************");
                String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
                if(BusinessType==null||BusinessType==""){
                    BusinessType = pPay.getBusinessType();
                }
                //请求通联callout
                logger.info("***************************请求通联支付宝支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+pPayCust.getCustId());
                Map<String, String> map = callOut_tlPublicService.pay(pPay.getPayAmount(), TimeStamp, pType, BusinessType, pPay.getPayRemark(), "000000", constantConfig.getTlReturnURL(),pPayCust);
                logger.info("***************************通联支付宝响应参数："+map.toString());
                //   Map<String, String> map = service.pay("1", TimeStamp, pType,pPay.getBusinessType(), pPay.getPayRemark(), "000000", FinalUtil.TL_RETURN_URL);
                //支付成功更新账单retcode：SUCCESS 请求成功 trxstatus：0000 拿到支付链接
                if ("SUCCESS".equals(map.get("retcode").toUpperCase()) && "0000".equals(map.get("trxstatus"))) {
                    PPay pPayUpdate = new PPay();
                    pPayUpdate.setGuid(paymentId);
                    pPayUpdate.setUpdateDate(new Date());
                    pPayUpdate.setPayInfoUrl(map.get("payinfo"));//支付链接
                    pPayUpdate.setTrxid(map.get("trxid"));//通联唯一流水单号
                    pPayUpdate.setPayType(pType);
                    pPayService.update(pPayUpdate);
                }
                JSONObject Object = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("gobackurl", pPay.getGoBackUrl());
                jsonObject.put("payinfo", alipayScanToApp(map.get("payinfo")));
                jsonObject.put("paymentId", pPay.getGuid());
                Object.put("errorCode", "0000");
                Object.put("errorMessage", "SUCCESS");
                Object.put("data", jsonObject);
                return Object;
            }else if ("W03".equals(pType)){     //微信支付
                logger.info("****************微信支付开始******************");
                String BusinessType =  sCodeNameService.getNameByCode(pPay.getBusinessType());
                if(BusinessType==null||BusinessType==""){
                    BusinessType = pPay.getBusinessType();
                }
                //请求通联callout
                logger.info("***************************请求通联微信支付："+pPay.getPayAmount()+"*******>>>>>pPayCust："+pPayCust.getCustId());
                Map<String, String> map = callOut_tlPublicService.payWeChat(pPay.getPayAmount(), TimeStamp, pType, BusinessType, pPay.getPayRemark(),pPay, constantConfig.getTlReturnURL(),pPayCust);
                logger.info("***************************通联微信响应参数："+map.toString());
                //   Map<String, String> map = service.pay("1", TimeStamp, pType,pPay.getBusinessType(), pPay.getPayRemark(), "000000", FinalUtil.TL_RETURN_URL);
                //支付成功更新账单retcode：SUCCESS 请求成功 trxstatus：0000 拿到支付链接
                if ("SUCCESS".equals(map.get("retcode").toUpperCase()) && "0000".equals(map.get("trxstatus"))) {
                    PPay pPayUpdate = new PPay();
                    pPayUpdate.setGuid(paymentId);
                    pPayUpdate.setUpdateDate(new Date());
                    pPayUpdate.setPayInfoUrl(map.get("payinfo"));//APP支付返回调起sdk的参数json字符串
                    pPayUpdate.setTrxid(map.get("trxid"));//通联唯一流水单号
                    pPayUpdate.setPayType(pType);
                    pPayService.update(pPayUpdate);
                }
                JSONObject Object = new JSONObject();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("gobackurl", pPay.getGoBackUrl());
                jsonObject.put("payinfo", map.get("payinfo"));
                jsonObject.put("paymentId", pPay.getGuid());
                Object.put("errorCode", "0000");
                Object.put("errorMessage", "SUCCESS");
                Object.put("data", jsonObject);
                return Object;

            }else {  //H5快捷支付
               List<PPayCUPUser> pPayCUPUsers = pPayCupUserService.findCUPUserByMeruserid(pPay.getPayUserSfGuid(), pPay.getEstateGuid());
               if(pPayCUPUsers == null ){ //首次使用银联支付
                   JSONObject Object = new JSONObject();
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("paymentId", pPay.getGuid());
                   Object.put("errorCode", "8888");  //8888需要绑卡
                   Object.put("errorMessage", "SUCCESS");
                   Object.put("data", jsonObject);
                   return Object;

               }else{
                   JSONObject Object = new JSONObject();
                   JSONObject json = new JSONObject();
                   JSONArray jsonArray = new JSONArray();
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("paymentId", pPay.getGuid());
                   Object.put("errorCode", "9999");  //8888需要绑卡
                   Object.put("errorMessage", "SUCCESS");
                   Object.put("data", jsonObject);
                   for (PPayCUPUser cup:
                   pPayCUPUsers) {
                       json.put("bankName",cup.getPayBankname());
                       json.put("bankCode",bankType(cup.getPayBankname()));
                       json.put("agreeid",cup.getPayAgreeid());
                       jsonArray.add(json);
                   }
                   Object.put("banks", jsonArray);
                   return Object;

               }

            }
        }
        return null;
    }

    /**
     * 将支付宝的二维码支付方式转化为app支付
     *
     * @param qrurl 例如 https://qr.alipay.com/bax00493ktpkya6i13s6002f
     * @return
     */
    public static String alipayScanToApp(String qrurl) {
        qrurl = qrurl + "?_s=web-other";//1.二维码url后面拼接?_s=web-other"
        String appUrl = "";
        try {
            qrurl = URLEncoder.encode(qrurl, "Utf8");//2.将拼接后urlecode
            qrurl = "alipays://platformapi/startapp?saId=10000007&clientVersion=3.7.0.0718&qrcode=" + qrurl;//在前面拼接打开支付宝app的方式
            appUrl = "https://ds.alipay.com/?from=mobilecodec&scheme=" + URLEncoder.encode(qrurl, "Utf8");//在前面再拼接跳往支付宝的url

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return appUrl;
    }

    /**
     * 根据小区sfid查询通联账户信息
     * @param estateGuid
     * @return
     */
    public PPayCust getTLMessage(String estateGuid ,String payType){
        return pPayCustService.getBySfGuid1(estateGuid,payType);
    }
    /**
     * 根据银行名字获取响应的logo
     * @param bankName
     * @return
     */
    public String  bankType(String bankName){
        String bankCode = "";
        switch(bankName){
            case "工商银行": bankCode = "ICBC_logo_01@2x.png"; break;
            case "农业银行": bankCode = "ABC_logo_02@2x.png"; break;
            case "交通银行": bankCode = "BCM_logo_03@2x.png"; break;
            case "建设银行": bankCode = "CCB_logo_04@2x.png"; break;
            case "中国银行": bankCode = "BOC_logo_05@2x.png"; break;
            case "招商银行": bankCode = "CMB_logo_06@2x.png"; break;
            case "光大银行": bankCode = "CEB_logo_07@2x.png"; break;
            case "上海银行": bankCode = "Shanghai_logo_08@2x.png"; break;
            case "北京银行": bankCode = "BOB_logo_09@2x.png"; break;
            case "农村信用社":
            case "合作社":   bankCode = "RCC_logo_10@2x.png"; break;
            case "浦发银行": bankCode = "SPDBank_logo_11@2x.png"; break;
            case "兴业银行": bankCode = "SG_logo_12@2x.png"; break;
            case "华夏银行": bankCode = "HXB_logo_13@2x.png"; break;
            case "中信银行": bankCode = "CITIC_logo_14@2x.png"; break;
            case "浙商银行": bankCode = "CZB_logo_15@2x.png"; break;
            case "广东发展": bankCode = "GDB_logo_16@2x.png"; break;
            case "民生银行": bankCode = "CMBC_logo_17@2x.png"; break;
            case "中国人民银行": bankCode = "PBC_logo_18@2x.png"; break;
            default: bankCode = "default_logo_19@2x.png"; break;
        }
        return  bankCode;
    }


}
